﻿namespace Contoso.ActiveDirectory {

    #region Usings
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.DirectoryServices;
    using System.Diagnostics;
    using System.Threading; 
    #endregion

    /// <summary>
    /// When querying for an ExchangeDatabase, the base DN should be: CN=Microsoft Exchange,CN=Services,[configuration naming context DN]
    /// </summary>
    [Serializable]
    public class ExchangeDatabase : ADBaseObjectProperties {

        #region Members
        public string AdminDisplayName { get; private set; }

        public string LegacyExchangeDN { get; private set; }

        public int DeletedItemFlags { get; private set; }

        public bool IsExchange2003 {
            get {
                return (this.MSExchVersion == ActiveDirectory.MSExchVersion.Undefined);
            }
        }

        public string MSExchMasterServerOrAvailabilityGroup { get; private set; }

        public string MSExchOwningServer { get; private set; }

        public MSExchVersion MSExchVersion { get { return msExchVersion; } }
        private MSExchVersion msExchVersion;

        public static readonly string ObjectCategoryShortName = "msExchPrivateMDB";
        #endregion

        #region Constructor
        public ExchangeDatabase() {
            this.Initialize();
        } 

        public ExchangeDatabase(DirectoryEntry directoryEntry, bool destroyInputObject = true)
            : base(directoryEntry, destroyInputObject) {
                if (this.GetType().Name == typeof(ExchangeDatabase).Name) {
                this.Attributes = null;
            }
        }

        public ExchangeDatabase(SearchResult result, bool destroyInputObject = true)
            : base(result, destroyInputObject) {
                if (this.GetType().Name == typeof(ExchangeDatabase).Name) {
                this.Attributes = null;
            }
        }

        public ExchangeDatabase(List<string> ldifOutput)
            : base(ldifOutput) {
                if (this.GetType().Name == typeof(ExchangeDatabase).Name) {
                this.Attributes = null;
            }
        }
        #endregion

        #region Methods
        protected override void Initialize() {
            base.Initialize();

            this.AdminDisplayName = string.Empty;
            this.LegacyExchangeDN = string.Empty;
            this.MSExchMasterServerOrAvailabilityGroup = string.Empty;
            this.MSExchOwningServer = string.Empty;
            msExchVersion = MSExchVersion.Undefined;
        }
        protected override void ProcessResults() {

            try {
                base.ProcessResults();

                if (this.Attributes.ContainsKey("adminDisplayName")) {
                    this.AdminDisplayName = this.Attributes["adminDisplayName"][0].ToString();
                }
                if (this.Attributes.ContainsKey("legacyExchangeDN")) {
                    this.LegacyExchangeDN = this.Attributes["legacyExchangeDN"][0].ToString();
                }
                if (this.Attributes.ContainsKey("deletedItemFlags")) {
                    this.DeletedItemFlags = Convert.ToInt32(this.Attributes["deletedItemFlags"][0]);
                }
                if (this.Attributes.ContainsKey("msExchMasterServerOrAvailabilityGroup")) {
                    this.MSExchMasterServerOrAvailabilityGroup = this.Attributes["msExchMasterServerOrAvailabilityGroup"][0].ToString();
                }
                if (this.Attributes.ContainsKey("msExchOwningServer")) {
                    this.MSExchOwningServer = this.Attributes["msExchOwningServer"][0].ToString();
                }
                if (this.Attributes.ContainsKey("msExchVersion")) {
                    Enum.TryParse<MSExchVersion>(this.Attributes["msExchVersion"][0].ToString(), result: out msExchVersion);
                }

                this.IsValid = !string.IsNullOrWhiteSpace(this.DN)
                    && this.ObjectClass.Any(x => string.Equals(x, ObjectCategoryShortName, StringComparison.OrdinalIgnoreCase));            
            }
            catch (Exception e) {
                Debug.WriteLine(string.Format("{0}  [ThreadID: {1}]  {2} Error: {3}", DateTime.Now.TimeOfDay, Thread.CurrentThread.ManagedThreadId, CustomExtensions.CurrentMethodName(), e.VerboseExceptionString()));
                throw;
            }
        } 
        #endregion

    }
}
